package com.lframework.jh.push.manage.controller;

import com.lframework.jh.push.core.annotations.security.HasPermission;
import com.lframework.jh.push.core.components.resp.InvokeResult;
import com.lframework.jh.push.core.components.resp.InvokeResultBuilder;
import com.lframework.jh.push.core.controller.DefaultBaseController;
import com.lframework.jh.push.core.utils.CollectionUtil;
import com.lframework.jh.push.core.utils.StringUtil;
import com.lframework.jh.push.manage.bo.role.QueryRoleMenuBo;
import com.lframework.jh.push.service.entity.SysMenu;
import com.lframework.jh.push.service.service.SysMenuService;
import com.lframework.jh.push.service.service.SysRoleMenuService;
import com.lframework.jh.push.service.vo.role.SysRoleMenuSettingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色授权
 *
 * @author zmj
 */
@Api(tags = "角色授权")
@Validated
@RestController
@RequestMapping("/system/role/menu")
public class SysRoleMenuController extends DefaultBaseController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 查询角色菜单列表
     */
    @ApiOperation("查询角色菜单列表")
    @ApiImplicitParam(value = "角色ID", name = "roleId", paramType = "query")
    @HasPermission({"system:role:permission"})
    @GetMapping("/menus")
    public InvokeResult<List<QueryRoleMenuBo>> menus(String roleId) {

        List<QueryRoleMenuBo> results = CollectionUtil.emptyList();
        //查询所有菜单
        List<SysMenu> allMenu = sysMenuService.queryList();
        if (!CollectionUtil.isEmpty(allMenu)) {
            results = allMenu.stream().map(QueryRoleMenuBo::new).collect(Collectors.toList());

            if (!StringUtil.isBlank(roleId)) {
                List<SysMenu> menus = sysMenuService.getByRoleId(roleId);
                if (!CollectionUtil.isEmpty(menus)) {
                    //当角色的菜单存在时，设置已选择属性
                    for (QueryRoleMenuBo result : results) {
                        result.setSelected(
                                menus.stream().anyMatch(t -> StringUtil.equals(t.getId(), result.getId())));
                    }
                }
            }
        }

        return InvokeResultBuilder.success(results);
    }

    /**
     * 授权角色菜单
     */
    @ApiOperation("授权角色菜单")
    @HasPermission({"system:role:permission"})
    @PostMapping("/setting")
    public InvokeResult<Void> setting(@Valid @RequestBody SysRoleMenuSettingVo vo) {

        sysRoleMenuService.setting(vo);
        return InvokeResultBuilder.success();
    }
}
